package com.epfresh.fragment;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.epfresh.R;
import com.epfresh.activity.BookActivity;
import com.epfresh.activity.CityAddressSelectedActivity;
import com.epfresh.activity.ColumnDetailActivity;
import com.epfresh.activity.CommonStoreActivity;
import com.epfresh.activity.DcStoreActivity;
import com.epfresh.activity.DetailGoodsActivity;
import com.epfresh.activity.GoodsAndMerchantActivity;
import com.epfresh.activity.HomeSecondAreaActivity;
import com.epfresh.activity.LoginActivity;
import com.epfresh.activity.MineAttentionActivity;
import com.epfresh.activity.MoreDeliveryCenterActivity;
import com.epfresh.activity.MyOrderActivity;
import com.epfresh.activity.OftenListActivity;
import com.epfresh.activity.PerfectInfoActivity;
import com.epfresh.activity.SearchActivity;
import com.epfresh.activity.WebActivity;
import com.epfresh.adapter.BannerViewBinderNew;
import com.epfresh.adapter.BaseSpellGoodsViewBinder;
import com.epfresh.adapter.DeliveryCenterViewBinderNew;
import com.epfresh.adapter.HomeColumnViewBinder;
import com.epfresh.adapter.HomeFootViewBinder;
import com.epfresh.adapter.LimitedTimeSpecialViewBinder;
import com.epfresh.adapter.MarketViewBinderNew;
import com.epfresh.adapter.OftenAreaViewBinderNew;
import com.epfresh.adapter.ViewBinderAd;
import com.epfresh.adapter.ViewBinderHomeOftenTitle;
import com.epfresh.adapter.ViewBinderOftenList;
import com.epfresh.api.constant.AppPurchaseRouterConstant;
import com.epfresh.api.entity.City;
import com.epfresh.api.entity.RequestEntityMap;
import com.epfresh.api.entity.RequestEntityPurchase;
import com.epfresh.api.entity.RequestTag;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.entity.StatusEntity;
import com.epfresh.api.helper.ApplicationHelper;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.universalimageloader.core.DisplayImageOptions;
import com.epfresh.api.universalimageloader.core.ImageLoader;
import com.epfresh.api.universalimageloader.core.assist.ImageScaleType;
import com.epfresh.api.utils.LocalDisplay;
import com.epfresh.api.utils.NetworkUtil;
import com.epfresh.api.utils.T;
import com.epfresh.api.utils.ToastUtils;
import com.epfresh.api.widget.ptr.PtrDefaultHandler;
import com.epfresh.api.widget.ptr.PtrFrameLayout;
import com.epfresh.api.widget.ptr.PtrHandler;
import com.epfresh.bean.BaseSpellGoodsBean;
import com.epfresh.bean.DistributionCenterEntity;
import com.epfresh.bean.HomeColumnBean;
import com.epfresh.bean.HomeTopEntityNew;
import com.epfresh.bean.LimitedTimeSpecialBean;
import com.epfresh.bean.NewHomeBean;
import com.epfresh.bean.OftenAreaBean;
import com.epfresh.bean.OftenListCategoryBean;
import com.epfresh.bean.OftenTitle;
import com.epfresh.bean.ResultBean;
import com.epfresh.bean.TopBannerEntity;
import com.epfresh.constant.Constant;
import com.epfresh.global.BaseApplication;
import com.epfresh.global.BaseFragment;
import com.epfresh.global.DataManager;
import com.epfresh.jsbridge.JsBridge;
import com.epfresh.utils.NetworkUtils;
import com.epfresh.views.CustomAlertDialog;
import com.epfresh.views.HomeCountDownView;
import com.epfresh.views.HomeOutRecyclerView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import multitype.MultiTypeAdapter;

public class HomeFragmentNew extends BaseFragment implements HomeCountDownView.OnCountDownListener, JsBridge.homeActJsCallback {
    //    private HomeOutRecyclerView rv_home_frag;
    private RecyclerView rv_home_frag;
    private MultiTypeAdapter multiAdapter;
    private List<Object> items = new ArrayList<>();
    private PtrFrameLayout ptrFrameLayout;

//    private ViewBinderOftenList viewBinderOftenList;

    //    private OftenTitle oftenTitle = new OftenTitle();
//    private OftenListCategoryBean oftenListCategoryBean;
    private LimitedTimeSpecialViewBinder limitedTimeSpecialViewBinder;
    private BaseSpellGoodsViewBinder baseSpellGoodsViewBinder;
    private HomeColumnViewBinder homeColumnViewBinder;

    private TextView tv_city;
    private ImageView bg_toolbar;
    private ImageView iv_act_home;
    private boolean isInit = true;
    private JsBridge jsBridge;

    @Override
    public String getBaseTag() {
        return "homeFragmentNew";
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_home_new, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
        refresh();
    }

    @SuppressLint("ClickableViewAccessibility")
    private void initView(View view) {
        jsBridge = new JsBridge();
        jsBridge.setHomeActJsCallback(this);

        bg_toolbar = view.findViewById(R.id.bg_toolbar);
        tv_city = view.findViewById(R.id.tv_city);
        tv_city.setOnClickListener(this);
        ImageView iv_city = view.findViewById(R.id.iv_city);
        iv_city.setOnClickListener(this);
        ImageView img_locate = view.findViewById(R.id.img_locate);
        img_locate.setOnClickListener(this);
        iv_act_home = view.findViewById(R.id.iv_act_home);
        iv_act_home.setOnClickListener(this);
        iv_act_home.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                moveDistance = LocalDisplay.getScreenWidth(getAppActivity()) - iv_act_home.getRight() + iv_act_home.getWidth() / 2;
                int i = LocalDisplay.getScreenWidth(getAppActivity()) - iv_act_home.getRight();
                int i1 = iv_act_home.getWidth() / 2;
                Log.e("moveDistance:", i + "+++++" + i1);
                //监听结束之后移除监听事件
                iv_act_home.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
        });

        view.findViewById(R.id.ll_search).setOnClickListener(this);

        rv_home_frag = view.findViewById(R.id.rv_home_frag);
        ptrFrameLayout = view.findViewById(R.id.ptr_fragment_home);
        ptrFrameLayout.setPtrHandler(ptrHandler);

        multiAdapter = new MultiTypeAdapter();
        BannerViewBinderNew bannerViewBinderNew = new BannerViewBinderNew(getAppActivity());
        bannerViewBinderNew.setOnBannerClickListener(new BannerViewBinderNew.OnBannerClickListener() {

            @Override
            public void onBannerClick(NewHomeBean.BannersBean bannersBean) {
                switch (bannersBean.getType()) {
                    case 1:
                        Intent h5Intent = new Intent(getAppActivity(), WebActivity.class);
                        h5Intent.putExtra(Constant.KEY_WEB_URL, bannersBean.getLink());
                        h5Intent.putExtra(Constant.KEY_WEB_TITLE, bannersBean.getTitle());
                        startActivity(h5Intent);
                        break;
                    case 2:
                        Intent storeIntent = new Intent(getAppActivity(), CommonStoreActivity.class);//整货店铺
                        storeIntent.putExtra("storeId", bannersBean.getStoreId());
                        startActivity(storeIntent);
                        break;
                    case 3:
                        Intent intent = new Intent(getAppActivity(), DetailGoodsActivity.class);
                        intent.putExtra("id", String.valueOf(bannersBean.getProductId()));
                        intent.putExtra("storeId", String.valueOf(bannersBean.getStoreId()));
                        startActivity(intent);
                        break;
                    default:
                        break;
                }
            }
        });
        OftenAreaViewBinderNew oftenAreaViewBinderNew = new OftenAreaViewBinderNew();
        oftenAreaViewBinderNew.setOnIconClickListener(new OftenAreaViewBinderNew.OnIconClickListener() {
            @Override
            public void onIconClick(int type) {
                if (!DataManager.getInstance().haveToken()) {
                    startActivity(new Intent(getAppActivity(), LoginActivity.class));
                    return;
                }
                switch (type) {
                    case 0:
                        Intent oftenIntent = new Intent(getActivity(), OftenListActivity.class);
                        startActivity(oftenIntent);
                        break;
                    case 1:
                        Intent orderList = new Intent(getActivity(), MyOrderActivity.class);
                        startActivity(orderList);
                        break;
                    case 2:
                        Intent attention = new Intent(getActivity(), MineAttentionActivity.class);
                        attention.putExtra("name", "我的关注");
                        startActivity(attention);
                        break;
                    case 3:
                        Intent book = new Intent(getActivity(), BookActivity.class);
                        startActivity(book);
                        break;
                    default:
                        break;
                }
            }
        });
        MarketViewBinderNew marketViewBinderNew = new MarketViewBinderNew(getAppActivity());
        marketViewBinderNew.setOnMarketClickListener(new MarketViewBinderNew.OnMarketClickListener() {
            @Override
            public void toMarket(NewHomeBean.MarketsBean item) {
                Intent intent = new Intent(getAppActivity(), GoodsAndMerchantActivity.class);
                intent.putExtra("marketId", String.valueOf(item.getId()));
                startActivity(intent);
            }

            @Override
            public void onAdClick(NewHomeBean.MarketsBean item) {
                switch (item.getMarketing().getType()) {
                    case 1:
                        Intent h5Intent = new Intent(getAppActivity(), WebActivity.class);
                        if (item.getMarketing().getLink().contains("active.html") && !TextUtils.isEmpty(getUser().getAccess_token())) {
                            h5Intent.putExtra(Constant.KEY_WEB_URL, item.getMarketing().getLink() + "&access_token=" + getUser().getAccess_token());
                        } else {
                            h5Intent.putExtra(Constant.KEY_WEB_URL, item.getMarketing().getLink());
                        }
                        h5Intent.putExtra(Constant.KEY_WEB_TITLE, item.getMarketing().getTitle());
                        startActivity(h5Intent);
                        break;
                    case 2:
                        Intent storeIntent = new Intent(getAppActivity(), CommonStoreActivity.class);
                        storeIntent.putExtra("storeId", item.getMarketing().getStoreId());
                        startActivity(storeIntent);
                        break;
                    case 3:
                        Intent intent = new Intent(getAppActivity(), DetailGoodsActivity.class);
                        intent.putExtra("id", String.valueOf(item.getMarketing().getProductId()));
                        intent.putExtra("storeId", String.valueOf(item.getMarketing().getStoreId()));
                        startActivity(intent);
                        break;
                    default:
                        break;
                }
            }
        });

        DeliveryCenterViewBinderNew deliveryCenterViewBinderNew = new DeliveryCenterViewBinderNew();
        deliveryCenterViewBinderNew.setOnDeliveryCenterClickListener(new DeliveryCenterViewBinderNew.OnDeliveryCenterClickListener() {
            @Override
            public void OnMoreCenterClick() {
                MobclickAgent.onEvent(getAppActivity(), "Click_Home_SendCenterMore");
                Intent intent = new Intent(getAppActivity(), MoreDeliveryCenterActivity.class);
                startActivity(intent);
            }

            @Override
            public void OnCenterClick(DistributionCenterEntity item, int centerPos, int type) {
                if (type == 0) {
                    Intent tv_bulk_load = new Intent(getActivity(), DcStoreActivity.class);//跳转到配送中心详情
                    tv_bulk_load.putExtra("storeId", item.getDistributionBeanList().get(centerPos).getId() + "");
                    startActivity(tv_bulk_load);
                }
                if (type == 1) {
                    T.toast("会员申请中，请等待");
                }
                if (type == 2) {
                    showAlertDialog(item.getDistributionBeanList().get(centerPos).getName(), item.getDistributionBeanList().get(centerPos).getId() + "");
                }
            }
        });

//        viewBinderOftenList = new ViewBinderOftenList(this);

        ViewBinderHomeOftenTitle viewBinderHomeOftenTitle = new ViewBinderHomeOftenTitle();
//        viewBinderHomeOftenTitle.context = this;
        limitedTimeSpecialViewBinder = new LimitedTimeSpecialViewBinder();
        limitedTimeSpecialViewBinder.setCountDownListener(this);
        limitedTimeSpecialViewBinder.setOnItemClickListener(new LimitedTimeSpecialViewBinder.OnItemClickListener() {
            @Override
            public void onMoreClick(LimitedTimeSpecialBean item) {
                Intent intent = new Intent(getActivity(), HomeSecondAreaActivity.class);
                intent.putExtra("seckillStoreId", item.getSeckillStoreId());
                startActivity(intent);
            }

            @Override
            public void onLimitedTimeGoodClick(NewHomeBean.SpikeBean spikeBean) {
                Intent intent = new Intent(getActivity(), DetailGoodsActivity.class);
                intent.putExtra("storeId", spikeBean.getProduct().getStoreId());
                intent.putExtra("id", spikeBean.getProduct().getId());
                intent.putExtra("promotionItemId", spikeBean.getPromotionItemId());
                startActivity(intent);
            }
        });
        baseSpellGoodsViewBinder = new BaseSpellGoodsViewBinder();
        baseSpellGoodsViewBinder.setOnItemClickListener(new BaseSpellGoodsViewBinder.OnItemClickListener() {
            @Override
            public void onMoreClick(BaseSpellGoodsBean item) {
                Intent intent = new Intent(getAppActivity(), WebActivity.class);
                intent.putExtra(Constant.KEY_WEB_URL, com.epfresh.api.constant.Constant.URL_BASE_SPELL_LIST +
                        "storeId=" + item.getStoreId() +
                        "&cityId=" + ApplicationHelper.getInstance().getCity().getCityId() +
                        "&isShare=false");
                intent.putExtra(Constant.KEY_WEB_TITLE, "产地拼货");
                intent.putExtra("storeId", item.getStoreId() + "");
                intent.putExtra("cityId", ApplicationHelper.getInstance().getCity().getCityId());
                startActivity(intent);
            }

            @Override
            public void onGoodClick(NewHomeBean.SpellsBean spellsBean) {
                Intent intent = new Intent(getAppActivity(), DetailGoodsActivity.class);
                intent.putExtra("id", String.valueOf(spellsBean.getId()));
                intent.putExtra("storeId", String.valueOf(spellsBean.getStoreId()));
                startActivity(intent);
            }
        });
        homeColumnViewBinder = new HomeColumnViewBinder();
        homeColumnViewBinder.setOnItemClickListener(new HomeColumnViewBinder.OnItemClickListener() {
            @Override
            public void onMoreClick(HomeColumnBean homeColumnBean) {
                Intent intent = new Intent(getAppActivity(),ColumnDetailActivity.class);
                intent.putExtra("title",homeColumnBean.getName());
                intent.putExtra("columnId",String.valueOf(homeColumnBean.getColumnId()));
                startActivity(intent);
            }

            @Override
            public void onColumnProductClick(HomeColumnBean.ProductsBean productsBean) {
                Intent intent = new Intent(getActivity(), DetailGoodsActivity.class);
                intent.putExtra("storeId", String.valueOf(productsBean.getStoreId()));
                intent.putExtra("id", String.valueOf(productsBean.getProductSpecPrice().getProductSpecId()));
                startActivity(intent);
            }
        });
        ViewBinderAd viewBinderAd = new ViewBinderAd(getAppActivity());
        viewBinderAd.setOnAdClickListener(new ViewBinderAd.OnAdClickListener() {
            @Override
            public void onAdClick(NewHomeBean.HomeAdBean item) {
                switch (item.getType()) {
                    case 1:
                        Intent h5Intent = new Intent(getAppActivity(), WebActivity.class);
                        h5Intent.putExtra(Constant.KEY_WEB_URL, item.getLink());
                        h5Intent.putExtra(Constant.KEY_WEB_TITLE, item.getTitle());
                        startActivity(h5Intent);
                        break;
                    case 2:
                        Intent storeIntent = new Intent(getAppActivity(), CommonStoreActivity.class);
                        storeIntent.putExtra("storeId", item.getStoreId());
                        startActivity(storeIntent);
                        break;
                    case 3:
                        Intent intent = new Intent(getAppActivity(), DetailGoodsActivity.class);
                        intent.putExtra("id", String.valueOf(item.getProductId()));
                        intent.putExtra("storeId", String.valueOf(item.getStoreId()));
                        startActivity(intent);
                        break;
                    default:
                        break;
                }
            }
        });
        HomeFootViewBinder homeFootViewBinder = new HomeFootViewBinder();
        multiAdapter.register(TopBannerEntity.class, bannerViewBinderNew);
        multiAdapter.register(OftenAreaBean.class, oftenAreaViewBinderNew);
        multiAdapter.register(NewHomeBean.MarketsBean.class, marketViewBinderNew);
        multiAdapter.register(DistributionCenterEntity.class, deliveryCenterViewBinderNew);
        multiAdapter.register(LimitedTimeSpecialBean.class, limitedTimeSpecialViewBinder);
        multiAdapter.register(BaseSpellGoodsBean.class, baseSpellGoodsViewBinder);
        multiAdapter.register(NewHomeBean.HomeAdBean.class, viewBinderAd);
        multiAdapter.register(HomeColumnBean.class,homeColumnViewBinder);
        multiAdapter.register(String.class, homeFootViewBinder);
//        multiAdapter.register(OftenTitle.class, viewBinderHomeOftenTitle);
//        multiAdapter.register(OftenListCategoryBean.class, viewBinderOftenList);

        multiAdapter.setItems(items);
        rv_home_frag.addOnScrollListener(new RecyclerView.OnScrollListener() {
            //
//            @Override
//            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
//                super.onScrolled(recyclerView, dx, dy);
//
//                if (items.contains(oftenListCategoryBean)) {
//
//                    int firstPos = ((LinearLayoutManager) recyclerView.getLayoutManager()).findFirstVisibleItemPosition();
//                    int flagPos = items.indexOf(oftenListCategoryBean);
//
//                    if (firstPos == flagPos) {
//                        viewBinderOftenList.setTabBgShow(true);
//                    } else {
//                        viewBinderOftenList.setTabBgShow(false);
//                    }
//                }
//            }
//
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                /**
                 * RecyclerView.SCROLL_STATE_IDLE:静止0
                 * RecyclerView.SCROLL_STATE_DRAGGING:拖拽滚动1
                 * RecyclerView.SCROLL_STATE_SETTLING:自己滚动2
                 */
                Log.e("newState:", newState + "");
                if (iv_act_home.getVisibility() == View.VISIBLE) {
                    if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                        upTime = System.currentTimeMillis();
                        isFreOperation = false;
                        if (!isShowFloatImage) {
                            timer = new Timer();
                            timer.schedule(new FloatTask(), 1000);
                        }
                    } else {
                        if (System.currentTimeMillis() - upTime < 1500) {
                            //本次按下距离上次的抬起小于1.5s时，取消Timer
                            isFreOperation = true;
                            timer.cancel();
                        }
                        if (isShowFloatImage) {
                            hideFloatImage(moveDistance);
                        }
                    }
                }

            }
        });
//        rv_home_frag.setOnTouchListener(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                switch (event.getAction()) {
//                    case MotionEvent.ACTION_DOWN:
//                        if (System.currentTimeMillis() - upTime < 1000) {
//                            //本次按下距离上次的抬起小于1.5s时，取消Timer
//                            timer.cancel();
//                        }
//                        startY = event.getY();
//                        break;
//                    case MotionEvent.ACTION_MOVE:
//                        if (Math.abs(startY - event.getY()) > 5) {
//                            if (isShowFloatImage) {
//                                hideFloatImage(moveDistance);
//                            }
//                        }
//                        startY = event.getY();
//                        break;
//                    case MotionEvent.ACTION_UP:
//                        if (!isShowFloatImage) {
//                            upTime = System.currentTimeMillis();
//                            timer = new Timer();
//                            //抬起手指1.5s后再显示悬浮按钮
//                            timer.schedule(new FloatTask(), 1000);
//                        }
//                        break;
//                    default:
//                        break;
//                }
//                return false;
//            }
//        });
        rv_home_frag.setLayoutManager(new LinearLayoutManager(getAppActivity()));
        rv_home_frag.setAdapter(multiAdapter);

        tv_city.setText(ApplicationHelper.getInstance().getCity().getCityName());
    }

    private PtrHandler ptrHandler = new PtrHandler() {
        @Override
        public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
            return PtrDefaultHandler.checkContentCanBePulledDown(frame, rv_home_frag, header);
        }

        @Override
        public void onRefreshBegin(PtrFrameLayout frame) {
            refresh();
        }
    };

    public void refresh() {
//        reqHomeTop(ApplicationHelper.getInstance().getCity().getCityId(), null, null);
        reqHome(ApplicationHelper.getInstance().getCity().getCityId(), null, null);
    }

    /**
     * 请求获取主页上半部分显示数据(包括banner/市场/配送中心)
     *
     * @param cityId
     * @param lng
     * @param lat
     */
    public void reqHomeTop(final String cityId, String lng, String lat) {
        RequestEntityMap requestEntity = new RequestEntityMap();

        requestEntity.setCmd(AppPurchaseRouterConstant.cmd_home_top);
        requestEntity.setCityId(cityId);
        requestEntity.putParameter("cityId", cityId);
        requestEntity.putParameter("lng", lng);
        requestEntity.putParameter("lat", lat);

        request(requestEntity, AppPurchaseRouterConstant.cmd_home_top, new OnRequestListener<HomeTopEntityNew>() {
            @Override
            public HomeTopEntityNew jsonToObj(String responseStr) {
                return new Gson().fromJson(responseStr, HomeTopEntityNew.class);
            }

            @Override
            public void onFail(int failCode, Object arg, Object tag) {
                T.toast(failCode + "");
                hideProgressDialog();
                ptrFrameLayout.refreshComplete();
            }

            @Override
            public void onResponseError(int failCode, Object arg, Object tag) {
                T.toast(failCode + "");
                hideProgressDialog();
                ptrFrameLayout.refreshComplete();
            }

            @Override
            public void onStart(Object tag) {
                if (isInit) {
                    showProgressDialog();
                    isInit = false;
                }
            }

            @Override
            public void onResponse(ResponseEntity<HomeTopEntityNew> response, Object tag) {
                items.clear();

                City city = ApplicationHelper.getInstance().getCity();
                String cityName = response.getResponseElement().getCityName();
                String cityCode = String.valueOf(response.getResponseElement().getCityCode());
                if (TextUtils.isEmpty(cityName)) {
                    cityName = ApplicationHelper.getInstance().getCity().getCityName();
                }
                if (TextUtils.isEmpty(cityCode)) {
                    cityCode = cityId;
                }
                city.setCityName(cityName);
                city.setCityId(cityCode);
                city.syncAddressId();
                ApplicationHelper.getInstance().updateCity(city);
                tv_city.setText(cityName);

//                //背景
//                if (response.getResponseElement().getBackgrounds() != null && response.getResponseElement().getBackgrounds().size() != 0) {
//                    ImageLoader.getInstance().displayImage(response.getResponseElement().getBackgrounds().get(0).getImgExtendPath(), bg_toolbar, options);
//                } else {
//                    ImageLoader.getInstance().displayImage("", bg_toolbar, options);
//                }
//                //顶部banner
//                if (response.getResponseElement().getBanners() != null && response.getResponseElement().getBanners().size() != 0) {
//                    TopBannerEntity topBannerEntity = generateTopBannerEntity(response.getResponseElement());
//                    items.add(topBannerEntity);
//                }
//                //批发市场
//                if (response.getResponseElement().getMarkets() != null && response.getResponseElement().getMarkets().size() != 0) {
//                    for (int i = 0; i < response.getResponseElement().getMarkets().size(); i++) {
//                        if (i == 0 && items.size() == 0) {
//                            if (response.getResponseElement().getBackgrounds() != null && response.getResponseElement().getBackgrounds().size() != 0) {
//                                response.getResponseElement().getMarkets().get(i).setBgUrl(response.getResponseElement().getBackgrounds().get(0).getImg());
//                            }
//                            response.getResponseElement().getMarkets().get(i).setChangBg(true);
//                        } else {
//                            response.getResponseElement().getMarkets().get(i).setChangBg(false);
//                        }
//                    }
//                    items.addAll(response.getResponseElement().getMarkets());
//                }
//                //配送中心
//                if (response.getResponseElement().getDistribution() != null && response.getResponseElement().getDistribution().size() != 0) {
//                    DistributionCenterEntity distributionCenterEntity = generateDistributionCenterEntity(response.getResponseElement());
//                    items.add(distributionCenterEntity);
//                }
//                //常购清单Title
//                items.add(oftenTitle);
//                isCompleted();
//                DataManager.getInstance().updateCartCnt();
//                reqOftenCategory();
            }
        });

    }

    /**
     * 构建顶部banner的数据
     *
     * @param responseElement
     * @return
     */
    private TopBannerEntity generateTopBannerEntity(NewHomeBean responseElement) {
        TopBannerEntity topBannerEntity = new TopBannerEntity();
        topBannerEntity.setImgBanners(responseElement.getBanners());
        if (responseElement.getBackgrounds() != null && responseElement.getBackgrounds().size() != 0) {
            topBannerEntity.setBgBanner(responseElement.getBackgrounds().get(0).getImg());
        }
        return topBannerEntity;
    }

    /**
     * 构建配送中心数据结构
     *
     * @param responseElement
     * @return
     */
    private DistributionCenterEntity generateDistributionCenterEntity(NewHomeBean responseElement) {
        DistributionCenterEntity distributionCenterEntity = new DistributionCenterEntity();

        distributionCenterEntity.setDisMore(responseElement.getDisMore());
        distributionCenterEntity.setDistributionBeanList(responseElement.getDistribution());

        return distributionCenterEntity;
    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_city:
            case R.id.img_locate:
                Intent address = new Intent(getActivity(), CityAddressSelectedActivity.class);
                startActivity(address);
                break;

            case R.id.ll_search:
                Intent search = new Intent(getActivity(), SearchActivity.class);
                startActivity(search);
                break;
            case R.id.iv_act_home:
                //if (canClick) {
                //canClick = false;
                if (NetworkUtils.isNetworkAvailable(getActivity())) {
                    showCustomAct();
                } else {
                    ToastUtils.TextToast(getContext(), "当前未连接网络");
                }
                pressAnim();
                //}
                break;
        }
    }


    private DisplayImageOptions options = new DisplayImageOptions.Builder()
            .showImageOnLoading(R.mipmap.bg_toolbar_main) //设置图片在下载期间显示的图片
            .showImageForEmptyUri(R.mipmap.bg_toolbar_main)//设置图片Uri为空或是错误的时候显示的图片
            .showImageOnFail(R.mipmap.bg_toolbar_main)
            .cacheInMemory(true)// 设置下载的图片是否缓存在内存中
            .cacheOnDisk(true)// 设置下载的图片是否缓存在SD卡中
            .considerExifParams(true) // 是否考虑JPEG图像EXIF参数（旋转，翻转）
            .imageScaleType(ImageScaleType.EXACTLY_STRETCHED)// 设置图片以如何的编码方式显示
            .bitmapConfig(Bitmap.Config.RGB_565)
            .build();


    //###################################################################################################################################################

    /**
     * 请求获取主页常购清单tab数据
     */
//    private void reqOftenCategory() {
//        RequestEntityMap requestEntity = new RequestEntityMap();
//        requestEntity.setCmd(AppPurchaseRouterConstant.cmd_store_offen_oftenList);
//        requestEntity.putParameter("topCategoryId", "");
//        requestEntity.putParameter("pageNumber", 0);
//        requestEntity.putParameter("pageSize", "10");
//        requestEntity.setCityId(ApplicationHelper.getInstance().getCity().getCityId());
//
//        request(requestEntity, AppPurchaseRouterConstant.cmd_store_offen_oftenList, new OnRequestListener<OftenListCategoryBean>() {
//            @Override
//            public OftenListCategoryBean jsonToObj(String responseStr) {
//                return new Gson().fromJson(responseStr, OftenListCategoryBean.class);
//            }
//
//            @Override
//            public void onFail(int failCode, Object arg, Object tag) {
//                T.toast(failCode + "");
//            }
//
//            @Override
//            public void onResponseError(int failCode, Object arg, Object tag) {
//                T.toast(failCode + "");
//            }
//
//            @Override
//            public void onStart(Object tag) {
//
//            }
//
//            @Override
//            public void onResponse(ResponseEntity<OftenListCategoryBean> response, Object tag) {
//                hideProgressDialog();
//                ptrFrameLayout.refreshComplete();
//                oftenListCategoryBean = response.getResponseElement();
//
//                if (oftenListCategoryBean.getTopCategory() != null && oftenListCategoryBean.getTopCategory().size() > 0) {
//                    oftenTitle.setHaveMore(ViewBinderHomeOftenTitle.OFTENHAVE);
//                    items.add(oftenListCategoryBean);
//
//                    if (viewBinderOftenList != null) {
//                        viewBinderOftenList.setTabTitles(getTabTitles(oftenListCategoryBean));
//                        viewBinderOftenList.setFragmentList(getFragmentList(oftenListCategoryBean));
//                        viewBinderOftenList.setInit(true);
//                    }
//
//                } else {
//                    oftenTitle.setHaveMore(ViewBinderHomeOftenTitle.OFTENNO);
//                }
//                multiAdapter.notifyDataSetChanged();
//            }
//        });
//    }


    /**
     * 得到所对应的tabTitles
     *
     * @param oftenListCategoryBean
     * @return
     */
    private List<String> getTabTitles(OftenListCategoryBean oftenListCategoryBean) {
        List<String> tabTitles = new ArrayList<>();
        for (OftenListCategoryBean.TopCategoryBean topCategoryBean : oftenListCategoryBean.getTopCategory()) {
            tabTitles.add(topCategoryBean.getName());
        }
        return tabTitles;
    }

    /**
     * 得到fragmentList
     *
     * @param oftenListCategoryBean
     * @return
     */
    private List<BaseFragment> getFragmentList(OftenListCategoryBean oftenListCategoryBean) {
        List<BaseFragment> fragmentList = new ArrayList<>();
        int pos = -1;
        for (OftenListCategoryBean.TopCategoryBean topCategoryBean : oftenListCategoryBean.getTopCategory()) {
            pos += 1;
            OftenListGoodsFrag oftenListGoodsFrag = new OftenListGoodsFrag();
            Bundle bundle = new Bundle();
            bundle.putString("categoryId", topCategoryBean.getId());
            bundle.putInt("tabPos", pos);
            oftenListGoodsFrag.setArguments(bundle);
            fragmentList.add(oftenListGoodsFrag);
        }
        if (fragmentList.get(0) != null) {
            ((OftenListGoodsFrag) fragmentList.get(0)).setFirstInit(true);
        }

        return fragmentList;
    }

    /**
     * 改变外层RecyclerView的拦截事件
     *
     * @param isNeedPass true：不拦截；false：拦截
     */
    public void adjustPass(boolean isNeedPass) {
//        rv_home_frag.setNeedPass(isNeedPass);
    }


    /**
     * 常购清单小红点
     *
     * @param has
     */
    public void setOftenTitleHasRedTip(boolean has) {
//        oftenTitle.setHasRedRound(has);
//        if (multiAdapter != null) {
//            multiAdapter.notifyDataSetChanged();
//        }

    }

    /**
     * 动态删除tab所对应的列表
     *
     * @param tabPos
     */
    public void removeOftenTab(int tabPos) {
//        List<OftenListCategoryBean.TopCategoryBean> topCategory = oftenListCategoryBean.getTopCategory();
//        topCategory.remove(tabPos);
//        if (topCategory.size() == 0) {
//            items.remove(items.size() - 1);
//            oftenTitle.setHaveMore(ViewBinderHomeOftenTitle.OFTENNO);
//        } else {
//            if (viewBinderOftenList != null) {
//                viewBinderOftenList.setTabTitles(getTabTitles(oftenListCategoryBean));
//                viewBinderOftenList.setFragmentList(getFragmentList(oftenListCategoryBean));
//                viewBinderOftenList.setInit(true);
//            }
//        }
//        multiAdapter.notifyDataSetChanged();
    }

    private void showAlertDialog(String strStoreName, final String storeId) {
        final CustomAlertDialog alertDialog = new CustomAlertDialog(getAppActivity());
        alertDialog.setTitles(Html.fromHtml("您正在向<font color=\"#24AF75\">“" + strStoreName + "”</font>申请会员"))
                .setTitleColor("#313131")
                .setMessage("申请通过后可享受商户服务")
                .setMessageColor("#666666")
                .setNoVis(true)
                .setCancelOnTouchOutside(true)
                .setYesOnClickListener("确认", new CustomAlertDialog.YesOnClickListener() {
                    @Override
                    public void yesClick() {
                        applyVIP(storeId);
                        alertDialog.dismiss();
                    }
                })
                .setNoOnClickListener("取消", new CustomAlertDialog.NoOnClickListener() {
                    @Override
                    public void noClick() {
                        alertDialog.dismiss();
                    }
                })
                .show();
    }

    /**
     * 申请会员
     *
     * @param storeId
     */
    private void applyVIP(String storeId) {
        RequestEntityPurchase<Map<String, String>> data = new RequestEntityPurchase<>();
        data.setCmd(AppPurchaseRouterConstant.cmd_store_store_bind);
        Map<String, String> map = new HashMap<>();
        map.put("storeId", storeId);
        data.setParameters(map);

        request(data, AppPurchaseRouterConstant.cmd_store_store_bind, new OnRequestListener<StatusEntity>() {
            @Override
            public StatusEntity jsonToObj(String responseStr) {
                return new Gson().fromJson(responseStr, StatusEntity.class);
            }

            @Override
            public void onFail(int failCode, Object arg, Object tag) {
                hideProgressDialog();
                T.toast(failCode + "");
            }

            @Override
            public void onResponseError(int failCode, Object arg, Object tag) {
                hideProgressDialog();
                T.toast(failCode + "");
            }

            @Override
            public void onStart(Object tag) {
                showProgressDialog();
            }

            @Override
            public void onResponse(ResponseEntity<StatusEntity> response, Object tag) {
                hideProgressDialog();
                StatusEntity responseElement = response.getResponseElement();
                if (responseElement.isSuccess()) {
                    refresh();
                } else {
                    T.toast("申请失败");
                }
            }
        });
    }

    //*********************************************************************2019—4—17新版主页*******************************************************************

    private String curCityId;

    public void reqHome(final String cityId, String lng, String lat) {
        if (curCityId != null && !curCityId.equals(cityId)) {
            isInit = true;
        }
        curCityId = cityId;
//        isCompleted();
        checkHaveActivity();
        RequestEntityMap re = new RequestEntityMap();
        re.setCmd(AppPurchaseRouterConstant.cmd_home_new);
        re.setCityId(cityId);
        re.putParameter("cityId", cityId);
        re.putParameter("lng", lng);
        re.putParameter("lat", lat);

        request(re, AppPurchaseRouterConstant.cmd_home_new, new OnRequestListener<NewHomeBean>() {
            @Override
            public NewHomeBean jsonToObj(String responseStr) {
                return new Gson().fromJson(responseStr, NewHomeBean.class);
            }

            @Override
            public void onFail(int failCode, Object arg, Object tag) {
                hideProgressDialog();
                ptrFrameLayout.refreshComplete();
            }

            @Override
            public void onResponseError(int failCode, Object arg, Object tag) {
                hideProgressDialog();
                ptrFrameLayout.refreshComplete();
            }

            @Override
            public void onStart(Object tag) {
                if (isInit) {
                    showProgressDialog();
                    isInit = false;
                }
            }

            @Override
            public void onResponse(ResponseEntity<NewHomeBean> response, Object tag) {
                hideProgressDialog();
                ptrFrameLayout.refreshComplete();
                items.clear();

                City city = ApplicationHelper.getInstance().getCity();
                String cityName = response.getResponseElement().getCityName();
                String cityCode = String.valueOf(response.getResponseElement().getCityCode());
                if (TextUtils.isEmpty(cityName)) {
                    cityName = ApplicationHelper.getInstance().getCity().getCityName();
                }
                if (TextUtils.isEmpty(cityCode)) {
                    cityCode = cityId;
                }
                city.setCityName(cityName);
                city.setCityId(cityCode);
                city.syncAddressId();
                ApplicationHelper.getInstance().updateCity(city);
                tv_city.setText(cityName);

                //背景
                if (response.getResponseElement().getBackgrounds() != null && response.getResponseElement().getBackgrounds().size() != 0) {
                    ImageLoader.getInstance().displayImage(response.getResponseElement().getBackgrounds().get(0).getImgExtendPath(), bg_toolbar, options);
                } else {
                    ImageLoader.getInstance().displayImage("", bg_toolbar, options);
                }
                //顶部banner
                if (response.getResponseElement().getBanners() != null && response.getResponseElement().getBanners().size() != 0) {
                    TopBannerEntity topBannerEntity = generateTopBannerEntity(response.getResponseElement());
                    items.add(topBannerEntity);
                }
                //常购清单、订单等的入口区域
                OftenAreaBean oftenAreaBean = new OftenAreaBean();
                if (items.size() == 0) {
                    if (response.getResponseElement().getBackgrounds() != null && response.getResponseElement().getBackgrounds().size() != 0) {
                        oftenAreaBean.setBgUrl(response.getResponseElement().getBackgrounds().get(0).getImg());
                    }
                    oftenAreaBean.setChangBg(true);
                } else {
                    oftenAreaBean.setChangBg(false);
                }
                items.add(oftenAreaBean);
                //批发市场
                if (response.getResponseElement().getMarkets() != null && response.getResponseElement().getMarkets().size() != 0) {
                    items.addAll(response.getResponseElement().getMarkets());
                }
                //配送中心广告
                if (response.getResponseElement().getActDistribution() != null && response.getResponseElement().getActDistribution().getImg() != null) {
                    items.add(response.getResponseElement().getActDistribution());
                }
                //配送中心
                if (response.getResponseElement().getDistribution() != null && response.getResponseElement().getDistribution().size() != 0) {
                    DistributionCenterEntity distributionCenterEntity = generateDistributionCenterEntity(response.getResponseElement());
                    items.add(distributionCenterEntity);
                }
                //限时特价广告
                if (response.getResponseElement().getActSpecial() != null && response.getResponseElement().getActSpecial().getImg() != null) {
                    items.add(response.getResponseElement().getActSpecial());
                }
                //限时特价
                if (response.getResponseElement().getSeckills() != null && response.getResponseElement().getSeckills().size() != 0) {
                    limitedTimeSpecialViewBinder.setInit(true);
                    LimitedTimeSpecialBean limitedTimeSpecialBean = new LimitedTimeSpecialBean();
                    limitedTimeSpecialBean.setSpikeBeanList(response.getResponseElement().getSeckills());
                    limitedTimeSpecialBean.setSeckillBeginTime(response.getResponseElement().getSeckillBeginTime());
                    limitedTimeSpecialBean.setSeckillEndTime(response.getResponseElement().getSeckillEndTime());
                    limitedTimeSpecialBean.setSysDate(response.getResponseElement().getSysDate());
                    limitedTimeSpecialBean.setSeckillStoreId(response.getResponseElement().getSeckillStoreId());
                    limitedTimeSpecialBean.setSeckillTotal(response.getResponseElement().getSeckillTotal());
                    items.add(limitedTimeSpecialBean);
                }
                //产地直销广告
                if (response.getResponseElement().getActBase() != null && response.getResponseElement().getActBase().getImg() != null) {
                    items.add(response.getResponseElement().getActBase());
                }
                //产地直销
                if (response.getResponseElement().getSpells() != null && response.getResponseElement().getSpells().size() != 0 && response.getResponseElement().getSpellTotal() != null) {
                    baseSpellGoodsViewBinder.setInit(true);
                    BaseSpellGoodsBean baseSpellGoodsBean = new BaseSpellGoodsBean();
                    baseSpellGoodsBean.setStoreId(response.getResponseElement().getSpells().get(0).getStoreId());
                    baseSpellGoodsBean.setSpellsBeanList(response.getResponseElement().getSpells());
                    baseSpellGoodsBean.setSpellTotal(response.getResponseElement().getSpellTotal());
                    items.add(baseSpellGoodsBean);
                }
                //主页商品栏目
                if (response.getResponseElement().getColumn() != null && response.getResponseElement().getColumn().size() != 0) {
                    items.addAll(response.getResponseElement().getColumn());
                }

                if (items.size() > 0) {
                    String foot = "";
                    items.add(foot);
                }
                multiAdapter.notifyDataSetChanged();
                DataManager.getInstance().updateCartCnt();
            }
        });
    }

    @Override
    public void onCountDownListener(boolean isFinish) {

    }

    /**
     * 判断是否需要完善信息
     */
    public void isCompleted() {
        if (ApplicationHelper.getInstance().getUser().getAccess_token() == null) {
            updateActButtonStatus(false);
            return;
        }
        final RequestEntityMap requestEntity = new RequestEntityMap();
        requestEntity.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_account_acc_isCompleted);
        RequestTag requestTag = new RequestTag();
        request(requestEntity, requestTag, new OnRequestListener<ResultBean>() {
            @Override
            public ResultBean jsonToObj(String responseStr) {
                return new Gson().fromJson(responseStr, ResultBean.class);
            }

            @Override
            public void onFail(int failCode, Object arg, Object tag) {
                T.toast(failCode + "");
            }

            @Override
            public void onResponseError(int failCode, Object arg, Object tag) {
                T.toast(failCode + "");
            }

            @Override
            public void onStart(Object tag) {
            }

            @Override
            public void onResponse(ResponseEntity<ResultBean> response, Object tag) {
                ResultBean responseElement = response.getResponseElement();
                if (!responseElement.isResult()) {
                    Intent complete = new Intent(getContext(), PerfectInfoActivity.class);
                    complete.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(complete);
                } else {
                    checkHaveActivity();
                }

            }
        });
    }

    private void checkHaveActivity() {
        RequestEntityMap re = new RequestEntityMap();
        re.setCmd(AppPurchaseRouterConstant.cmd_activity_turntable);
        re.setCityId(curCityId);
        request(re, AppPurchaseRouterConstant.cmd_activity_turntable, new OnRequestListener<Map<String, Object>>() {
            @Override
            public Map<String, Object> jsonToObj(String responseStr) {
                return new Gson().fromJson(responseStr, new TypeToken<Map<String, Object>>() {
                }.getType());
            }

            @Override
            public void onFail(int failCode, Object arg, Object tag) {

            }

            @Override
            public void onResponseError(int failCode, Object arg, Object tag) {

            }

            @Override
            public void onStart(Object tag) {

            }

            @Override
            public void onResponse(ResponseEntity<Map<String, Object>> response, Object tag) {
                Map<String, Object> responseElement = response.getResponseElement();
                boolean isLucky = (boolean) responseElement.get("isLucky");
                boolean isOpen = (boolean) responseElement.get("isOpen");
                boolean button = (boolean) responseElement.get("button");
                updateActButtonStatus(button);
//                Toast.makeText(getAppActivity(), "" + button, Toast.LENGTH_LONG).show();
                if (isLucky && isOpen) {
                    showCustomAct();
                }
            }
        });
    }

    private Dialog dialogAct;
    private WebView webAct;
    //private boolean canClick = true;

    @SuppressLint({"SetJavaScriptEnabled", "AddJavascriptInterface"})
    private void showCustomAct() {
        if (dialogAct == null) {
            dialogAct = new Dialog(getAppActivity(), R.style.no_title_dialog);

            View contentView = getLayoutInflater().inflate(R.layout.custom_act, null);
            webAct = contentView.findViewById(R.id.wv_act);
            WebSettings settings = webAct.getSettings();
            settings.setJavaScriptEnabled(true);//启用js
            settings.setJavaScriptCanOpenWindowsAutomatically(true);//js和android交互
            settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
            settings.setAllowFileAccess(true); // 允许访问文件
            settings.setAppCacheEnabled(false); //设置H5的缓存打开,默认关闭
            settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);//设置，可能的话使所有列的宽度不超过屏幕宽度
            settings.setLoadWithOverviewMode(true);//设置webView自适应屏幕大小
            settings.setDomStorageEnabled(true);//设置可以使用localStorage
            settings.setSupportZoom(false);//关闭zoom按钮
            settings.setBuiltInZoomControls(false);//关闭zoom
            webAct.setLayerType(View.LAYER_TYPE_HARDWARE, null);
            webAct.addJavascriptInterface(jsBridge, "JsBridge");
            webAct.setWebViewClient(new WebViewClient() {
                @Override
                public void onPageFinished(WebView view, String url) {
//                    if (!dialogAct.isShowing()) {
//                        dialogAct.show();
//                    }
                    //canClick = true;
                    super.onPageFinished(view, url);
                }

                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    return super.shouldOverrideUrlLoading(view, url);
                }
            });
            webAct.setWebChromeClient(new WebChromeClient());
            webAct.setBackgroundColor(0);
            webAct.getBackground().setAlpha(0);
            dialogAct.setCanceledOnTouchOutside(true);
            dialogAct.setContentView(contentView);
            Window window = dialogAct.getWindow();
            window.setGravity(Gravity.CENTER);
            WindowManager.LayoutParams lp = window.getAttributes();
            lp.width = getResources().getDisplayMetrics().widthPixels;
            lp.height = getResources().getDisplayMetrics().heightPixels;
            window.setAttributes(lp);
        }
        if (!dialogAct.isShowing()) {
            dialogAct.show();
        }
        Log.e("webview", com.epfresh.api.constant.Constant.URL_ACTIVITY_TURNTABLE +
                "?access_token=" + getUser().getAccess_token() +
                "&accountId=" + getUser().getAccountId() +
                "&cityId=" + curCityId);
        webAct.loadUrl(com.epfresh.api.constant.Constant.URL_ACTIVITY_TURNTABLE +
                "?access_token=" + getUser().getAccess_token() +
                "&accountId=" + getUser().getAccountId() +
                "&cityId=" + curCityId);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (webAct != null) {
            webAct.onResume();
            webAct.resumeTimers();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (webAct != null) {
            webAct.onPause();
            webAct.pauseTimers();
        }
    }

    @Override
    public void onDestroyView() {
        dialogAct = null;
        webAct = null;
        super.onDestroyView();
    }

    private boolean isShowFloatImage = true;
    private int moveDistance;
    private long upTime;
    private Timer timer;
    private boolean isFreOperation;

    /**
     * 显示悬浮图标
     *
     * @param distance
     */
    private void showFloatImage(int distance) {
        isShowFloatImage = true;
        //位移动画
        TranslateAnimation ta = new TranslateAnimation(
                distance,//起始x坐标
                0,//结束x坐标
                0,//起始y坐标
                0);//结束y坐标（正数向下移动）
        ta.setDuration(300);

        //渐变动画
        AlphaAnimation al = new AlphaAnimation(0.5f, 1f);
        al.setDuration(300);

        AnimationSet set = new AnimationSet(true);
        //动画完成后不回到原位
        set.setFillAfter(true);
        set.addAnimation(ta);
        set.addAnimation(al);
        iv_act_home.startAnimation(set);
    }

    /**
     * 隐藏悬浮图标
     *
     * @param distance
     */
    private void hideFloatImage(int distance) {
        isShowFloatImage = false;
        //位移动画
        TranslateAnimation ta = new TranslateAnimation(
                0,//起始x坐标,10表示与初始位置相距10
                distance,//结束x坐标
                0,//起始y坐标
                0);//结束y坐标（正数向下移动）
        ta.setDuration(300);

        //渐变动画
        AlphaAnimation al = new AlphaAnimation(1f, 0.5f);
        al.setDuration(300);

        AnimationSet set = new AnimationSet(true);
        //动画完成后不回到原位
        set.setFillAfter(true);
        set.addAnimation(ta);
        set.addAnimation(al);
        iv_act_home.startAnimation(set);
    }

    private void pressAnim() {
        ScaleAnimation sa = new ScaleAnimation(1.0f, 1.2f, 1.0f, 1.2f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        sa.setDuration(300);
        iv_act_home.startAnimation(sa);
    }

    private void updateActButtonStatus(boolean show) {
        //解决动画发生后visible属性无效问题
        iv_act_home.clearAnimation();
        iv_act_home.invalidate();
        if (show) {
            iv_act_home.setVisibility(View.VISIBLE);
        } else {
            iv_act_home.setVisibility(View.INVISIBLE);
        }
    }

    class FloatTask extends TimerTask {
        @Override
        public void run() {
            getAppActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (!isFreOperation)
                        showFloatImage(moveDistance);
                }
            });
        }
    }

    @Override
    public void closeHomeDialogAct() {
        if (dialogAct != null) {
            dialogAct.dismiss();
        }

    }

}
